package com.leanit.pmc.reg;

import com.leanit.pmc.common.util.VerifyCodeUtils;
import com.leanit.pmc.reg.bean.RegMail;
import com.leanit.pmc.reg.bean.RegVO;
import com.leanit.pmc.reg.service.RegService;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户登录controller
 *
 * @author
 */
@Controller
@RequestMapping("/reg")
public class RegController {


    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    RegService regService;
    @Value("${shiro.login.url}")
    private String loginUrl;

    @Value("${ecommerce.url}")
    private String ecommerceUrl;

    @Value("${ecommercejn.url}")
    private String ecommercejn;

    @Value("${index.url}")
    private String indexUrl;

    /**
     * 注册的1step 填写邮箱
     *
     * @return
     */
    @RequestMapping(value = "/stepOne", method = {RequestMethod.GET, RequestMethod.HEAD})
    public String stepOne(ModelMap modelMap,HttpSession session) {
        //注册之前先清空session
        try {
            SecurityUtils.getSubject().logout();
            session.invalidate();
        } catch (Exception e) {
            logger.error("", e);
        }

        modelMap.put("indexUrl", indexUrl);
        modelMap.put("loginUrl", loginUrl);
        return "reg/step_one";
    }

    /**
     * 注册的1step 填写邮箱
     *
     * @return
     */
    @RequestMapping(value = "/stepTwo", method = {RequestMethod.GET, RequestMethod.HEAD})
    public String validMail(String mailKey, ModelMap modelMap) {
        RegMail regMail = regService.getRegMail(mailKey);
        if (null == regMail || !regService.validMailKey(regMail.getMail(), regMail.getMailKey())) {
            return "reg/invalid_mail";
        }
        modelMap.put("regMail", regMail);
        return "reg/step_two";
    }

    /**
     * 注册的3step 注册成功
     *
     * @return
     */
    @RequestMapping(value = "/stepThree", method = {RequestMethod.GET, RequestMethod.HEAD})
    public String stepThree(String username, ModelMap modelMap,HttpSession session) {
        //注册之前先清空session
        try {
            SecurityUtils.getSubject().logout();
            session.invalidate();
        } catch (Exception e) {
            logger.error("", e);
        }
        modelMap.put("username", username);
        modelMap.put("loginUrl", loginUrl);
        modelMap.put("indexUrl", indexUrl);
        modelMap.put("ecommerceUrl", ecommerceUrl);
        modelMap.put("ecommercejnUrl", ecommercejn);
        return "reg/step_three";
    }

    /**
     * 注册的1step 填写邮箱
     *
     * @return
     */
    @RequestMapping(value = "/validMail", method = {RequestMethod.GET, RequestMethod.HEAD})
    public String validMail(String mail, String mailKey, ModelMap modelMap) {
        modelMap.put("mail", mail);
        modelMap.put("mailKey", mailKey);
        return "reg/valid_mail";
    }

    /**
     * 验证邮箱
     *
     * @param session
     * @param mail
     * @param code
     * @return
     */
    @RequestMapping(value = "/verifyMail", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/text; charset=utf-8")
    @ResponseBody
    public String verifyMail(HttpSession session, String mail, String code, String mailKey) throws IOException, TemplateException {
        if (VerifyCodeUtils.verifyCodeIgnoreCase(session, code)) {
            return regService.sendMail(mail);
        } else if (StringUtils.isNotEmpty(mailKey)) {
            return regService.sendMail(mail, mailKey);
        }
        return "验证码输入错误，请重新输入";
    }

    /**
     * 注册用户
     *
     * @param regInfo
     * @return
     */
    @RequestMapping(value = "/regUsr", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/text; charset=utf-8")
    @ResponseBody
    public String regUsr(RegVO regInfo) throws IOException, TemplateException {
        if (!regService.validMailKey(regInfo.getMail(), regInfo.getMailKey())) {
            return "无效的注册链接";
        }
        try {
            return regService.regUsr(regInfo);
        } catch (Exception e) {
            logger.error("保存用户失败", e);
            return "注册用户失败,请重试或者联系系统管理员";
        }
    }

    /**
     * 添加子用户
     *
     * @param userName
     * @param parentId
     * @param mail
     * @param phone
     * @return
     * @throws IOException
     * @throws TemplateException
     */
    @RequestMapping(value = "/addChildUsr", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/text; charset=utf-8")
    @ResponseBody
    public String regUsr(String userName, String parentId, String mail, String phone, String password) {
        try {
            return regService.addChildUsr(userName, parentId, mail, phone, password);
        } catch (Exception e) {
            logger.error("添加子用户失败", e);
            return "添加子用户失败,请重试或者联系系统管理员";
        }
    }

}
